<?php
/**
 * Created by PhpStorm.
 * User: zhanghua
 * Date: 2018/9/21
 * Time: 18:13
 */

namespace app\sun\service;


use app\common\service\ModelBaseService;
use app\sun\model\Admin;
use app\sun\model\AdminRole;
use app\sun\model\AdminRoleRelation;
use think\Db;
use think\Exception;


/**
 * Class AdminService
 * @package app\sun\service
 */
class AdminService extends ModelBaseService
{
    protected $modelName = 'app\\sun\\model\\Admin';

    /**
     * @var string
     */
    protected  $authPrefix = 'sunAuthAdmin';

    /**
     * 用户名密码登录
     * @param $username
     * @param $password
     * @return bool
     */
    protected function login($username, $password){

        $admin = Admin::get(['username' => $username ]);

        if(is_null($admin)) return false;

        if($admin->password === md5(md5($password) . $admin->salt)){
            session($this->authPrefix,$admin->id);

            return $admin->id;
        }

        return false;
    }


    /**
     * 退出系统
     */
    protected function logout(){
        session(null);
    }

    /**
     * 检查是否登录
     * @return bool|mixed  false:未登录 , int: 登录者id
     */
    protected function checkLogin(){

        $admin = session('sunAuthAdmin');

        return $admin ? $admin : false;
    }


    /**
     * 获取登录者的所有菜单信息
     * @param int $adminId
     * @return array|\PDOStatement|string|\think\Collection
     * @throws Exception
     */
    protected function getMenu($adminId=0)
    {
        $adminId = 1;//写死测试debug
        if(empty($adminId)){
            $adminId = $this->getLoginId();

            if(!$adminId){
                throw new Exception("请登录后再进行获取菜单");
            }
        }

        //SELECT c.* FROM sun_admin_role_relation a INNER JOIN sun_admin_role_perm_relation b ON a.role_id = b.role_id INNER JOIN sun_admin_perm c ON b.perm_id = c.id   WHERE a.admin_id = 1;
        $result = Db::table('sun_admin_role_relation')
            ->alias('a')
            ->Join('sun_admin_role_perm_relation b','a.role_id = b.role_id')
            ->Join('sun_admin_perm c','b.perm_id = c.id')
            ->where('a.admin_id', $adminId)
            ->field('c.*')
            ->select();
        return $result;
    }

    //是否有这个权限
    /**
     *
     */
    protected function hasPerm()
    {

    }

    /**
     * 没有登录就返回false, 登录就返回管理员id
     * @return bool|mixed
     */
    protected function getLoginId()
    {
        return $this->checkLogin();
    }

    protected function del($adminId)
    {
        $adminId = max(0, intval($adminId));
        Db::startTrans();
        try {
            Admin::destroy($adminId);
            AdminRoleRelation::destroy(function ($query) use ($adminId){
                $query->where('admin_id', $adminId);
            });
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception("删除不成功!");
        }
        return false;
    }


}